var COOKIE_CART_NAME = "cartList";

$(document).ready(function(){
	updateTopCart();
});

//region 加入购物车
function addToCart(picurl,callback){
	var divQuantity=$("#proinfo_quantity");
	//region 判断数量是否合法
	var num = parseInt(divQuantity.val().trim());
	if (isNaN(num)) {
		alert("请输入数量");
		divQuantity.focus();
		return;
	} else if (num < 1) {
		alert("数量不能小于1");
		divQuantity.focus().select();
		return;
	} else {
		divQuantity.val(num);
	}
	//endregion

	//region 获取详情页信息
	var cart = new Object();
	cart.PROID=$("#productID").val();
	cart.QUANTITY=num;
	cart.POINTS=parseInt($("#productPoints").text());
	cart.CREATETIME=new Date();
	cart.PRODUCTNAME=$("#productName").text();
	//if($("#productPicurl")[0]){
		cart.PRODUCTURL=picurl;
	/*}else{
		cart.PRODUCTURL=$(".bannerpd").src;
	}*/
	//endregion
		addProToCookie(cart);
	updateTopCart();
	if(typeof (callback) == "undefined"){
		alert("加入购物车成功！");
	}else{
		if(typeof (callback)=="function"){
			callback();
		}
	}
}
//endregion

//region 获取购物车列表
function getcartlist(callback)
{
	var cartList = new Array();
	$.get("/cart/list",{},function(data){
		if(data.result){
			cartList = data.rows;
			if(cartList==null){
				cartList= new Array();
			}
			if(typeof (callback)!="undefined" && typeof (callback)=="function"){
				callback(cartList);
			}
		}
		return cartList;
	},"json");
}
//endregion

//region 更新头部信息
function updateTopCart()
{
	getcartlist(rewriteTopCart);
}

//region 重写头部购物车信息
function rewriteTopCart(objList){
	$('#cartlist').children().remove();
	if(objList==null || objList.length==0){
		delCookie(COOKIE_CART_NAME);
		$('#cartNum').text(0);
		$('#cartlist').append('<p class="pt-1 pb-1 right-tit text-left cartitemtop"><strong>购物车中还没有商品，赶紧选购吧！</strong></p>');
		return;
	}else{
		$('#cartlist').append('<p class="pt-1 pb-1 right-tit text-left cartitemtop"><strong>最新加入的商品</strong></p>');
	}
	num = 0;
	allPoints = 0;
	var result = objList;
	if(result && result!=null && result.length>0){
		for(var i=0;i<result.length;i++){
			var obj = result[i];
			$('#cartlist').append('<div id="cart_'+obj.proid+'" class="pt-1 pb-1 right-tit cartitem '+(obj.stat==1?"":"underpro")+'">'
				+ '<div class="col-md-10 col-lg-10 col-xs-10 col-sm-10 p0 pull-left cartsubitem">'
				+ '<img class="dingdan-img pull-left" src="'+obj.picurl_n4+'">'
				+ '<p class="pull-left" style="width:220px;"><strong class="cartname">'+obj.productname+'</strong>'
				+ (obj.stat==1?"":"已下架")+'</div>'
				+ '<div class="col-md-2 col-lg-2 col-xs-2 col-sm-2 text-right p0 mt-2 pt-1" style="width:100px;"><span class="text-oriange">'+obj.points+'</span>积分x<span>'+obj.quantity+'</span></p><a href="javascript:;" onclick="deleteCart('+obj.proid+')">删除</a></div>'
				+ '</div>');
			num = num + obj.quantity;
			allPoints = allPoints + obj.points*obj.quantity;
		}
	}
	$('#cartNum').text(num);
	$('#cartlist').append('<div class="cartjs">'
		+ '<div class="pull-left cartjs-left">'
		+ '<p class="text-center pl-1"><strong id="cartnum" class="text-oriange fz-14">'+num+'</strong>件商品&nbsp;&nbsp;&nbsp;&nbsp;共计：<strong id="cartpoints" class="text-oriange fz-14">'+allPoints+'</strong>积分</p>'
		+ '</div>'
		+ '<div class="pull-right btn-yes p0" style=" border:none;width: 120px; " >'
		+ '<a href="../cart/mycart"><button type="button" class="btn-yes fs-14 cartjs-right">去购物车</button></a>'
		+ '</div>'
		+ '</div>');
}
//endregion
//endregion

function deleteCart(proid){
	var cartListJsonStr = getCookie(COOKIE_CART_NAME);
	if(cartListJsonStr.length>0){
		delProFromCookie(proid);
		resetCartList(proid);
		return;
	}

		$.ajax({
			url: "/cart/delete?proid=" + proid,
			dataType: "json",
			success: function (data) {
				if (data.result) {
					resetCartList(proid);
				} else {
					//alert("删除失败!");
				}
			}
		});
}

function resetCartList(proid){
	if ($("#listcart_" + proid)) {
		$("#listcart_" + proid).remove();
		if (typeof (setTotal) == "function") {
			setTotal();
		}
	}
	updateTopCart();
}

//region 购物车Cookie操作
function addProToCookie(cart) {
	var objList = new List();
	var cartListJson = getCookie(COOKIE_CART_NAME);
	if (cartListJson.length > 0) {
		//region 已存在，更新Cookie
		var currCookieList = $.parseJSON(cartListJson);
		var isAddNew = true;
		for (var key in currCookieList) { //第一层循环取到各个list
			var cartList = currCookieList[key];
			for (var c in cartList) { //第二层循环取list中的对象
				if (cartList[c].PROID == cart.PROID) {
					cartList[c].QUANTITY = parseInt(cartList[c].QUANTITY) + cart.QUANTITY;
					isAddNew = false;
					objList = currCookieList;
					break;
				}
			}
		}
		if (isAddNew == true) {
			objList = $.parseJSON(cartListJson.substring(0, cartListJson.length - 2) + "," + JSON.stringify(cart) + "]}");
		}
		//endregion
	} else {
		objList.add(cart);
	}

	setCookie(COOKIE_CART_NAME,JSON.stringify(objList),365);
	//return objList;
}

function delProFromCookie(proid){
	var cartListJsonStr = getCookie(COOKIE_CART_NAME);
	var newCartList = new List();
	var cartJson = $.parseJSON(cartListJsonStr);
	if(cartJson.value && cartJson.value.length>0){
		var cartJsonArr = cartJson.value;
		for(var i=0;i<cartJsonArr.length;i++){
			var obj = cartJsonArr[i];
			if(parseInt(obj.PROID)!=parseInt(proid)){
				newCartList.add(obj);
			}
		}
	}
	if(newCartList.size()>0){
		setCookie(COOKIE_CART_NAME,JSON.stringify(newCartList),365);
		resetCartList(proid);
	}else{
		delCookie(COOKIE_CART_NAME);
		resetCartList(proid);
	}
}

function updProFromCookie(proid,quantity){
	var cartListJson = getCookie(COOKIE_CART_NAME);
	var obj = JSON.parse(cartListJson);
	for (var key in obj) { //第一层循环取到各个list
		var cartList = obj[key];
		for (var c in cartList) { //第二层循环取list中的对象
			if (cartList[c].PROID == proid) {
				cartList[c].QUANTITY = quantity;
				setCookie(COOKIE_CART_NAME, JSON.stringify(obj), 365);
			}
		}
	}
}
//endregion
